package com.ktjiaoyu.crm.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.lang.reflect.Method;
import java.time.Duration;
public class RedisConfig  extends CachingConfigurerSupport {
    /**
     * 自定义生成key的规则
     * @return
     */
    @Bean
    public KeyGenerator keyGenerator() {
        return new KeyGenerator() {
            @Override
            public Object generate(Object target, Method method, Object... params) {
                //格式化缓存key字符串
                StringBuilder sb = new StringBuilder();
                //追加类名
                sb.append(target.getClass().getName());
                //追加方法名
                sb.append(method.getName());
                //遍历参数并且追加
                for (Object obj : params) {
                    sb.append(obj.toString());
                }
                return sb.toString();
            }
        };
    }

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        // 正确的泛型类型
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);

        // 使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        ObjectMapper objectMapper = new ObjectMapper();
        // 设置对象的所有属性都是可访问的
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        // 开启对象的默认类型识别，避免反序列化时出现类型丢失
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);

//    jackson2JsonRedisSerializer.setObjectMapper(objectMapper);

        // 设置value的序列化方式和反序列化方式
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);

        // 设置key的序列化方式，这里使用StringRedisSerializer
        redisTemplate.setKeySerializer(new StringRedisSerializer());

        // 如果使用hash结构存储，也需要设置hashKey和hashValue的序列化方式
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);

        // 初始化模板
        redisTemplate.afterPropertiesSet();

        return redisTemplate;
    }

    /**
     *
     * 采用RedisCachManager作为缓存管理器
     * @param factory
     * @return
     */
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory){
        //创建Redis序列化对象
        RedisSerializer<String> redisSerializer=new StringRedisSerializer();
        //创建Jackson对象
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer=new Jackson2JsonRedisSerializer(Object.class);

        ObjectMapper om=new ObjectMapper();

        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);


        RedisCacheConfiguration config=RedisCacheConfiguration.defaultCacheConfig().
                entryTtl(Duration.ofDays(7)).serializeKeysWith(RedisSerializationContext.SerializationPair.
                        fromSerializer(redisSerializer)).serializeValuesWith(RedisSerializationContext.SerializationPair.
                        fromSerializer(jackson2JsonRedisSerializer)).disableCachingNullValues();
        RedisCacheManager cacheManager=RedisCacheManager.builder(factory).cacheDefaults(config).build();
        return cacheManager;
    }
}




